from django.shortcuts import render,redirect
from django.contrib.auth import login,authenticate
from .forms import ReadersCreationForm,ReadersChangeForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages

# Create your views here.
def register(request):
    if request.method=='POST':
        form=ReadersCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username=form.cleaned_data.get('username')
            raw_password=form.cleaned_data.get('password1')
            user=authenticate(username=username,password=raw_password)
            login(request,user)
            return redirect('home')
    else:
        form=ReadersCreationForm()
    return render(request,'register.html',{'form':form})
#从templs文件夹下开始找的，所以↑如果有libraryapp就要再加一层目录

@login_required
def profile(request):
    if request.method=='POST':
        form=ReadersChangeForm(request.POST,instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request,'Profile updated successfully.')
            return redirect('profile')
    else:
        form=ReadersChangeForm(instance=request.user)
    return render(request,'profile.html',{'form':form})